package com.yenlien.traceyun.business.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author master yi
 */
public class UserAuthUtil {

    /**
     * 获取登录用户
     *
     * @return
     */
    public static UserInfo getLoginUser() {
        if (RequestContextHolder.getRequestAttributes() != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (!StringUtils.isEmpty(token)) {
                return TokenUtil.getUserInfo(token);
            } else {
                Object user = request.getSession().getAttribute("user");
                if (user == null) {
                    throw new BusinessException("未登录");
                }
                return (UserInfo) user;
            }
        }
        throw new BusinessException("未登录");
    }
}
